import * as deptService from '../../services/department';

export default {
  namespace: 'department',
  state: {
    deptTree: [],
    deptList: [],
    current : 1,
    currentSize : 10,
    total : 0, 
    pid : 1,  
    currentItem: {},
    modalType:'create',
    modalVisible:false,
  },
  reducers: {
    qryDeptsSuc(state, { payload: deptTree }) {
      return { ...state, deptTree };
    },
    qryDeptsByPidSuc(state, { payload }) {
      return { ...state, ...payload };
    },
    showModal (state, { payload }) {
      return { ...state, ...payload, newKey : new Date().getTime() + '' , modalVisible: true }
    },
    hideModal (state) {
      return { ...state, modalVisible: false,currentItem: {}, newKey : new Date().getTime() + '' }
    },
  },
  effects: {
    *qryDepts({ payload },{ call, put }) {
      const { body }  = yield call(deptService.qryDepts);
      yield put({ type: 'qryDeptsSuc', payload: body.data });
    },
    *qryDeptsByPid({ payload },{ call, put }) {
      const { body } = yield call(deptService.qryDeptsByPid,payload);
      yield put({ type: 'qryDeptsByPidSuc', payload: { deptList:body.data, current:body.current, currentSize:body.size, total:body.iTotalRecords, pid:payload.pid }});
    },

    *qryById({ payload },{ call, put }){
      yield put({
          type: 'showModal',
          payload: {
            currentItem: payload,
            modalType: 'edit',
          },
      });
    },

    *create({ payload,search },{ call, put }){
      const { body } = yield call(deptService.create,payload);
      yield put({ type: 'qryDeptsByPid',payload:search });
      yield put({ type: 'hideModal' });
    },
    *edit({ payload },{ call, put }){
      const { body } = yield call(deptService.edit,payload);
      yield put({ type: 'reload' });
      yield put({ type: 'hideModal' });
      
    },
    *remove({ payload },{ call, put }){
      const { body } = yield call(deptService.remove,payload.id);
      yield put({ type: 'qryDeptsByPid', payload:payload.search });
      yield put({ type: 'qryDepts' });
    },
    *reload(action, { put }) {
      yield put({ type: 'qryDeptsByPid', payload:{ 'pid':1,'name':'' }});
      yield put({ type: 'qryDepts' });
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/sys/dept') {
          dispatch({ type: 'qryDepts' });
          dispatch({ type: 'qryDeptsByPid', payload:{ 'pid':1,'name':'' }});
        }
      });
    },
  },
};
